<?php
namespace app\admin\controller;

use think\Controller;
use think\facade\Session;
use think\Db;

class Login extends Controller {

    // 公共
    public function __initialize()
    {
        if(Session::has('admin','mmjtAdmin')){
            $this->redirect('index/index');
        }
    }

    public function index() {
        if(request()->isAjax()){
            $name = input('post.name', false);
            $password = md5(input('post.password', false));
            $captcha = input('post.yzm', false);

            if($name && $password){
                if(!$captcha){
                    return ['err' => '请输入验证码'];
                }
                if(!captcha_check($captcha)){
                    return ['err' => '验证码错误'];
                };

                $admin = Db::name('admin')->where(['name' => $name, 'password' => $password])->find();

                if($admin) {
                    if($admin['hide'] <= 0 ){
                        $data = ['err' => '账户被禁用'];
                    } else {
                        Db::name('admin')->where('id', $admin['id'])->update(['update_time' => time(), 'update_ip' => $this->request->ip()]);
                        Session::set('admin', $admin,'mmjtAdmin');
                        $data = ['ret' => '登录成功,正在跳转...'];
                    }
                } else {
                    $data = ['err' => '账户或密码错误'];
                }
            } else {
                $data = ['err' => '请输入信息'];
            }
            return json($data);
        } else {
            return $this->fetch();
        }
    }
}
